package com.izhengyin.demo.concurrent.basic;

import com.izhengyin.demo.concurrent.SleepUtils;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * @author zhengyin
 * Created on 2021/11/30
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);
        //每隔5个，将间隔一秒后输出
        IntStream.rangeClosed(1,15)
            .forEach(i -> {
                Executors.newCachedThreadPool()
                        .execute(() -> {
                            try {
                                semaphore.acquire();
                                System.out.println(new Date()+" => "+i);
                                SleepUtils.sleep(1000);
                            }catch (InterruptedException e){
                                e.printStackTrace();
                            }finally {
                                semaphore.release();
                            }
                        });
            });

    }
}
